import _ from "underscore";
import moment from "moment";

import Vue from 'vue';

import api from '../api';
import dataDefault from "../data/taskDefault";
var plusAudio, h5audio;
import {
  mapState,
  mapActions
} from 'vuex'

let headBtnItem = { label: '执行模式<br/><span style="color:#10aeff;font-size:12px;">左滑任务</span><span style="color:#666;font-size:12px;">快速完成任务</span>', type: 'info' }; //,下拉页面有VIP高级功能
let taskBtnItem = { label: '详情', value: 'info' };
let startBtnItem = { label: '开始', value: 'started' };
let doneBtnItem = { label: '完成', value: 'done' };
let toggleBtnItem = { label: '暂停', value: 'toggle' };
let restartBtnItem = { label: '继续', value: 'restart' };
let noneBtnItem = { label: '重置', value: 'none' }; //重置复原
let todayBtnItem = { label: '今天就做', value: 'today' };
let tomorrowBtnItem = { label: '明天要做', value: 'tomorrow' };
let lastlocalId; //上次播放的微信语音,
let lastItem, touchTask;

export const help = {
  computed: {
    ...mapState({
      uid: state => state.vux.uid,
    })
  },
  data() {
    return {
      showEditBtn: false,
      asBtnCurr: [],
      daySwipe: "",
      today: moment().format("YYYY-MM-DD"),
      showSwipeDay: "",
      taskCurr: null,
      longvisible: false,
    }
  },
  methods: {
    parseDefault() {
      let tasks;
      let tasksTemp = dataDefault.tasks;
      let today = this.today; // moment().format("YYYY-MM-DD");
      var len = tasksTemp.length,
        temp, tempKey;
      for (var i = 0; i <= len - 1; i++) {
        var item = tasksTemp[i];
        if (item.tags != undefined) break; //第二次进入逻辑,已经转换过了.
        temp = i + 1;
        item.id = temp;
        item.tags = [];
        if (item.due == "today") {
          item.tags.push({ taskid: temp, id: temp, key: "due", value: today });
        }
        if (item.created == "today") {
          item.tags.push({ taskid: temp, id: temp, key: "created", value: today });
        }
        if (item.key != undefined) {
          tempKey = item.key.split(",");
          tempKey.forEach((key, index) => {
            item.tags.push({ taskid: temp, id: temp * 10 + index, key: key, value: '' });
          })
        }
        item.pid = item.pid != undefined && item.pid != "" ? item.pid : null;
        delete item.due;
        delete item.key;
      }
      this.$store.commit({ type: "z39/usertask", projs: dataDefault.projects });
      this.$store.commit({ type: "z39/taskToDB", tasks: tasksTemp, act: "add" });
      let actions = dataDefault.actionMove;
      len = actions.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = actions[i];
        temp = i + 1;
        item.id = temp;
        if (item.timeday == "today") {
          item.timeday = today;
        }
      }
      this.$store.commit({ type: "z39/actionSet", acts: actions });
    },
    importDefault() { //服务器已实现了导入默认数据,这里基本已经无用.可考虑删除
      let tasks;
      let tasksTemp = dataDefault.tasks;
      let today = moment().format("YYYY-MM-DD");
      var len = tasksTemp.length,
        temp, tempKey;
      for (var i = 0; i <= len - 1; i++) {
        var item = tasksTemp[i];
        if (item.tags != undefined) break; //第二次进入逻辑,已经转换过了.
        temp = i + 1;
        // item.id = temp;
        item.tags = {}; //[]
        if (item.due == "today") {
          item.tags["due"] = today;
        }
        if (item.created == "today") {
          item.tags["created"] = today;
        }
        if (item.key != undefined) {
          tempKey = item.key.split(",");
          tempKey.forEach((key, index) => {
            item.tags[key] = "";
            // item.tags.push({ taskid: temp, id: temp * 10 + index, key: key, value: '' });
          })
        }
        item.pid = item.pid != undefined && item.pid != "" ? item.pid : null;
        delete item.due;
        delete item.key;
        if (item.pid) continue; //需要在下面添加项目后在添加任务.
        api.taskAdd(item).then(data => {
          if (data == undefined) data = { errmsg: "网络错误", errno: 1001 };
          if (data.errno != 0) console.log("添加错误 ", item);
        })
      }
      len = dataDefault.projects.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = dataDefault.projects[i];
        api.projectAdd(item).then(data => {
          let pid = data.data; //真实项目id            
          if (data.errno != 0) return console.log("添加错误 ", item);
          tasksTemp.forEach((task, index) => {
            if (task.pid > 0 && task.pid == item.id) {
              task.pid = pid;
              api.taskAdd(task).then(data => {
                if (data == undefined) data = { errmsg: "网络错误", errno: 1001 };
                if (data.errno != 0) console.log("添加错误 ", task);
              })
            }
          })
        })
      }

      // this.$store.commit({ type: "z39/usertask", projs: dataDefault.projects });
      // this.$store.commit({ type: "z39/taskToDB", tasks: tasksTemp, act: "add" });
      let actions = dataDefault.actionMove;
      len = actions.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = actions[i];
        // temp = i + 1;
        // item.id = temp;
        if (item.timeday == "today") {
          item.timeday = today;
        }
        api.taskautoAdd(item).then(data => {
          if (data == undefined) data = { errmsg: "网络错误", errno: 1001 };
          if (data.errno != 0) console.log("添加错误 ", item);
        })
      }
      // this.$store.commit({ type: "z39/actionSet", acts: actions });
      let audios = dataDefault.audios;
      len = audios.length;
      for (var i = 0; i <= len - 1; i++) {
        var item = audios[i];
        api.audioAdd(item).then(data => {
          if (data == undefined || data.errno != 0) {
            if (data == undefined) data = { errmsg: "网络错误" };
            console.log("添加错误 ", item);
          }
        })
      }
    },
    initDefaultMd() { //初始化
      let tasks;
      let tasksTemp = [];
      dataDefault.tasks.forEach(item => {
        let newItem = Object.assign({}, item);
        tasksTemp.push(newItem); //push
      })
      let today = moment().format("YYYY-MM-DD");
      var len = tasksTemp.length,
        temp, tempKey, taskTags;
      // console.log("tasklen: ", len);
      for (var i = 0; i <= len - 1; i++) {
        var item = tasksTemp[i];
        // if (item.tags != undefined) break; //第二次进入逻辑,已经转换过了.
        temp = i + 1;
        // item.id = temp;
        item.tags = item.tags || {}; //[]
        taskTags = [];
        if (item.due == "today") {
          item.tags["due"] = today;
          taskTags.push({ key: "due", value: today });
        }
        if (item.created == "today") {
          item.tags["created"] = today;
          taskTags.push({ key: "created", value: today });
        }
        var temps = item.tags.started;
        if (temps && temps.length < 10) item.tags.started = today + " " + temps;
        var tempd = item.tags.done;
        if (tempd && tempd.length < 10) item.tags.done = today + " " + tempd;
        if (item.key != undefined) {
          tempKey = item.key.split(",");
          tempKey.forEach((key, index) => {
            item.tags[key] = "";
            taskTags.push({ key: key, value: '' });
            // item.tags.push({ taskid: temp, id: temp * 10 + index, key: key, value: '' });
          })
        }
        item.pid = (item.pid != undefined && item.pid != "") ? item.pid : null;
        delete item.due;
        delete item.key;
        if (item.pid) continue; //需要在下面添加项目后在添加任务.
        delete item.id;
      }
      // console.log("initDefaultMd:", tasksTemp);
      return tasksTemp;
    },
    checkInvite() {
      console.log("checkIvite in", this.uid, this.GetRequest());
      let params = this.GetRequest();
      let action = params.action;
      let type = params.type;
      let xid = params.xid;
      let pwd = params.pwd;
      let _this = this;
      if (action == 'invite' && !_.isEmpty(pwd)) {
        if (!this.uid) { //未登录就切换到登录页.
          return this.$router.push(`/login`); //this.$vux.toast.show({ text: '请先登录', type: 'warn' });
        }

        api.inviteTitleGet({ type, xid }).then(data => {
          if (data == undefined) data = { errmsg: "网络错误", errno: 1001 };
          if (data.errno != 0) return this.$vux.toast.show({ text: data.errmsg, type: 'warn' });
          setTimeout(() => {
            this.$vux.confirm.show({
              title: '邀请信息',
              content: `您是否加入'${data.data}'群?`,
              onCancel() {

              },
              onConfirm() {
                api.inviteGet({ type, xid, pwd }).then(idata => {
                  if (idata.errno != 0) return _this.$vux.toast.show({ text: idata.errmsg, type: 'warn' });
                  _this.$vux.toast.show({ text: idata.data, type: 'success' });
                });
              }
            })
          }, 1000)
        })
      }
    },
    getuser(code) {
      return api.getuser({
        code,
        href: window.location.href
      }).then(data => {
        if (data && data.errno == 0) {
          data = data.data;
          console.log("wx", data);
          if (data.token) window.localStorage.setItem('token', data.token);
          data.username = data.nickname;
          this.$store.commit(Object.assign({ type: "user" }, data));
          this.$store.commit({ type: "z39/reset" });
          try { this.usertask(); } catch (e) { console.error("import mixin.js") }
          this.checkInvite();
        } else { //发生错误.
          if (data.errno == 2000) window.location.href = data.redirect;
        }
      })
    },
    showIcons(item) {
      var name = 'logo';
      // done due due1 need none safe sort sort1 start summary task used            
      if (item.state == "") {
        if (item.tags && item.tags.due != undefined) {
          var now = moment().format("YYYY-MM-DD HH:mm");
          var due = item.tags.due;
          name = due.length > 10 && due > now ? 'due1' : 'due';
        } else if (item.tags && item.tags.need != undefined) {
          name = 'need';
        } else {
          name = 'logo';
        }
      } else if (item.state == "due") {
        var now = moment().format("YYYY-MM-DD HH:mm");
        var due = item.tags.due;
        name = due && due.length > 10 && due > now ? 'due1' : 'due';
      } else if (item.state == "started") {
        name = 'start';
      } else if (item.state == "toggle") {
        name = 'pause';
      } else if (item.state == "cancelled") {
        name = 'cancel';
      } else if (item.state == "summary") {
        name = 'summary';
      } else if (item.state == "done") {
        if (item.tags && item.tags.summary != undefined) {
          name = 'summary';
          // }else if(item.tags.sort !=undefined){
          //     name = 'sort' ;
        } else {
          name = 'done';
        }
      } else {
        name = 'logo';
      }
      let img = `/static/z39h5/img/${name}.png`;
      return img;
    },
    getTaskBtns(item, mode) {
      let arr = [];
      arr.push(headBtnItem);
      if (mode == 1 && item.tags && item.tags.due == undefined) {
        arr.push(todayBtnItem);
        arr.push(tomorrowBtnItem);
      }
      if (!item.tags || (item.tags.wakeup == undefined && item.tags.sleep == undefined && item.tags.workStart == undefined && item.tags.workEnd == undefined)) { //起床,睡觉时刻性格的生活任务只显示完成.
        if (item.state == "" || item.state == "due" || item.state == "need") {
          arr.push(startBtnItem);
        } else if (item.state == "started") {
          arr.push(toggleBtnItem);
        } else if (item.state == "toggle") {
          arr.push(restartBtnItem);
        }
      }
      if (item.state == "done") {
        arr.push(noneBtnItem);
      } else {
        arr.push(doneBtnItem);
      }
      arr.push(taskBtnItem);
      return arr;
    },
    chooseEdit(key, item) {
      console.log("chooseEdit", key, item);
      if (item == undefined) return; //点击取消或阴影直接关闭.      
      let task = this.taskCurr;
      if (!task.id) return this.addDemoTask(task, key); //默认展示数据
      if (!task.id) return this.$vux.toast.show({ text: "请创建任务" });
      this.doClickTask(item.value, task);
      // console.warn("chooseEdit:", key, item);
    },
    addDemoTask(item, state, ext) { //有taskid后才能后续操作
      var now = moment().format("YYYY-MM-DD HH:mm");
      var due = now;
      var sdata, tags;
      if (state == "info") state = ""; //查看的按钮值是info,调整成demo数据.
      sdata = { title: item.title, state };
      // tags = { done: now, due: now, created: now };
      if (state == "") tags = { created: now };
      else if (state == "done") tags = { done: now, due: now, created: now };
      else if (state == "started") tags = { created: now };
      if (ext) tags = Object.assign(tags, ext);
      return this.taskAdd(sdata, tags).then(data => { if (!data.errno) localStorage.setItem("firstrun", 1) });
    },
    doClickTask(clickKey, task, opts) {
      this.tongji("task", clickKey, "today", "click");
      // let task = this.taskCurr;
      if (clickKey == "top") {
        let tempIndex = this.todayArr.indexOf(task);
        // 删除上面元素,插入到当前index
        if (tempIndex > 0) {
          let pre = this.todayArr.splice(tempIndex, 1)[0];
          this.todayArr.splice(0, 0, pre);
          this.saveSort();
        } else {
          console.warn("已在最顶");
        }
      } else if (clickKey == "pre") {
        let tempIndex = this.todayArr.indexOf(task);
        // 删除上面元素,插入到当前index
        if (tempIndex > 0) {
          let pre = this.todayArr.splice(tempIndex - 1, 1)[0];
          this.todayArr.splice(tempIndex, 0, pre);
          this.saveSort();
        } else {
          console.warn("已在最顶");
        }
        console.log("index", tempIndex);
      } else if (clickKey == "started") {
        this.doTaskEdit(task, "started", moment().format("YYYY-MM-DD HH:mm"), opts).then((data) => {
          this.checkSetClock(task);
        });
      } else if (clickKey == "info") {
        this.goTask(task);
      } else if (clickKey == "toggle") {
        this.doTaskEdit(task, "toggle", moment().format("YYYY-MM-DD HH:mm"), opts);
      } else if (clickKey == "done") {
        this.doTaskEdit(task, "done", moment().format("YYYY-MM-DD HH:mm"), opts);
      } else if (clickKey == "none") {
        this.doTaskEdit(task, "");
      } else if (clickKey == "restart") {
        this.doTaskEdit(task, "toggle", moment().format("YYYY-MM-DD HH:mm"), opts);
      } else if (clickKey == "today") {
        this.doTaskEdit(task, "due", moment().format("YYYY-MM-DD"));
      } else if (clickKey == "tomorrow") {
        this.doTaskEdit(task, "due", moment().add(1, "d").format("YYYY-MM-DD"));
      } else {
        console.warn("may be error", key, item);
      }
    },
    showTaskDesc(item) {
      var res = "";
      if (item.tags) {
        if (item.tags.started) {
          res += item.tags.started.substr(11);
        }
        if (item.tags.done) {
          res = res || "?";
          res += "~" + item.tags.done.substr(11) + " ";
        } else if (item.tags.need) {
          if (!item.tags.started) {
            res += "评估[" + item.tags.need + "] ";
          } else {
            var nc = getSecond(item.tags.need);
            var done = moment().add(nc, 's').format("HH:mm");
            res += "~[" + done + "] ";
          }
        } else if (item.tags.started) {
          res += "~?";
        }
      }
      res += item.desc || "";
      return res;
    },
    showTaskDesc1(item) {
      var res = '';
      var tags = item.tags;
      if (!tags || (!tags.started && !tags.done && !tags.need)) return res;
      var due, started, done, need, used, usedCalc;
      res += tags.due ? `[${tags.due.substr(11,5)}]` : "[日程]";
      res += tags.started ? tags.started.substr(11, 5) : " 开始";
      res += tags.done ? `~${tags.done.substr(11,5)} ` : "~结束 ";
      if (tags.need) {
        var second = getSecond(tags.need);
        var need = moment("2018-04-10").add(second, 's').format("HH:mm:ss");
        res += `(${need}->`; // tags.need ?  : "(评估耗时->";
      } else {
        res += "(评估耗时->";
      }
      // res += tags.need ? `(${tags.need}->` : "(评估耗时->";
      res += tags.used || tags.usedCalc ? `${tags.used || tags.usedCalc})` : "实际消耗)";
      // if( item.tags['started'] || item.tags['done']){
      //     res = (item.tags['started']?item.tags['started'].substring(11):'[?]') + ' ~ ' + (item.tags['done']?item.tags['done'].substring(11):'[]') ;
      // }
      return res;
    },
    showTaskTitle(item) {
      var res = item.title;
      if ((item.state == "" || item.state == "due") && item.tags && item.tags.due && item.tags.due.length > 11) res = `[${item.tags.due.substr(11)}] ` + res;
      return res;
    },
    playtask(item, from) { //播放任务的音频
      console.log("playtask");
      this.tongji("task", "play", from, "");
      this.taskCurr = item;
      this.stopAllSound(item);
      if (lastItem && item == lastItem) return lastItem = null;
      if (Vue.device.isWechat && item.localId) {
        wx.onVoicePlayEnd({
          success: function(res) {
            var localId = res.localId;
            lastlocalId = null;
          }
        });
        wx.playVoice({ localId: item.localId });
        lastlocalId = item.localId;
      } else if (isApp && item.file) {
        this.playSoundApp(item.file);
      } else {
        if (item.aid) {
          api.audioGet({ id: item.aid }).then(data => {
            if (data.errno != 0) return this.$vux.toast.show({ text: data.errmsg, type: 'warn' });
            if (Vue.device.isWechat && data.data.localId) wx.playVoice({ localId: data.data.localId });
            else if (isApp && data.data.file) this.playSoundApp(data.data.file);
            else this.playSoundH5(data.data.url);
          })
        } else {
          api.audioTTS({ txt: item.title, ignore: 1 }).then(data => {
            if (data.errno != 0) return this.$vux.toast.show({ text: data.errmsg, type: 'warn' });
            else this.playSoundH5(data.data);
          })
        }
      }
      lastItem = item;
    },
    playSoundApp(url) {
      console.log("playSoundApp:", url);
      plusAudio = plus.audio.createPlayer(url);
      plusAudio.play(function() {});
    },
    playSoundH5(url) {
      console.log("playSoundH5:", url);
      if (isApp) plus.audio.createPlayer("static/z39h5/sound/nothing.mp3").play(function() {});
      h5audio = document.createElement("audio"); //new Audio(url); 不行
      h5audio.src = url;
      h5audio.play();
    },
    stopAllSound() {
      if (Vue.device.isWechat && lastlocalId) {
        wx.stopVoice({ localId: lastlocalId });
        lastlocalId = null;
      }
      if (plusAudio) plusAudio.stop();
      plusAudio = null;
      if (h5audio) h5audio.pause();
      h5audio = null;
    },
    dayshow: function(item, daySwipe) {
      var today = this.today; // moment().format("YYYY-MM-DD");
      var nextDay = moment().add(1, "d").format("YYYY-MM-DD");
      var day, letter = 'error';
      if (daySwipe) day = daySwipe;
      else if (!item.id) day = today; //默认展示数据
      else day = parseInt(moment().format("H")) > 12 ? nextDay : today; //超过12点就自动变为明天.
      if (day == "" || day == nextDay) letter = "明天";
      else if (day == today) letter = "今天";
      else letter = day.substr(5);
      this.showSwipeDay = day;
      return letter;
    },
    onTaskDue(item, index) {
      if (!item.id) return this.addDemoTask(item, "", { due: moment().format("YYYY-MM-DD") });
      let day = this.showSwipeDay;
      this.doTagSet(item, "due", day).then(data => {
        this.nonesCpted();
      });
      this.tongji("task", "due", this.pageName, "swipe");
    },
    doTaskTouchStart(item, index) {
      touchTask = item;
    },
    doLongtap() {
      this.onEdit(touchTask)
      this.tongji("task", "due", "todo", "longtap");
      console.log("token longtap")
    },
    onEdit(item, index) {
      this.taskCurr = item;
      let _this = this;
      let time = moment().format("H");
      time = parseInt(time);
      let temp;
      if (time >= 12) {
        temp = this.showMonth || moment().add(1, 'days').format("YYYY-MM-DD");
      } else {
        temp = this.showMonth || moment().format("YYYY-MM-DD");
      }
      this.longvisible = true;
      this.$vux.datetime.show({
        cancelText: '取消',
        confirmText: '确定',
        format: 'YYYY-MM-DD',
        startDate: moment().format("YYYY-MM-DD"),
        value: this.showMonth || temp,
        onConfirm(val) {
          _this.daySwipe = val;
          if (!item.id) return _this.addDemoTask(item, "", { due: val }).then(data => { _this.nonesCpted() });
          _this.showMonth = val;
          _this.doTagSet(item, "due", val).then(data => { _this.nonesCpted() });
          _this.tongji("task", "due", "todo", "set");
        },
        onShow() {
          console.log('plugin show')
        },
        onHide() {
          _this.longvisible = false;
          console.log('plugin hide')
        }
      })
      console.log(_.clone(item), temp, moment().format("YYYY-MM-DD"));
    },
    showTasnBtn(item, index) {
      this.taskCurr = item;
      this.showEditBtn = true;
      this.asBtnCurr = this.getTaskBtns(item);
      this.tongji("task", "taskbtns", this.pageName, "show"); //"todo", "show");
    },
    nonesCpted() { //待办分页使用的,这里避免项目分页报错.
    },
    showDue(item) {
      let txt = '';
      if (item.tags && item.tags['due']) {
        txt = moment(item.tags['due']).format('M-DD');
        txt = `[${txt}]`;
      }
      return txt;
    },
  }

}
